﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using CarolLib.WinService;
using DCS.Business.Interface;
using DCS.Business.Manager;
using DCS.Business.Model;
using DCS.DataProvider;
using Microsoft.Practices.Unity;
using Microsoft.Practices.Unity.Configuration;
using System.Threading;
using CarolLib;
using System.Configuration;
using System.Text.RegularExpressions;

namespace SITAMessageParser
{
    public class Parser : IMessageParser
    {

        #region members
        private static log4net.ILog Logger = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
        private static WinServiceSetting Settings = WinServiceConfiguration.GetConfig().Settings;
        private static SITAMessageManager manager;


        //private readonly Regex flightAirportReg = new Regex("^(\\S+)\\s+(\\S+)\\s*(.*)$");

        //private readonly Regex onDateReg = new Regex("^(.{0,5}ON)\\s+([0-9/]+)([A-Z]{3})([0-9]{0,4})$");

        //private readonly Regex fmDateReg = new Regex("^(.{0,5}FM|FROM)\\s+([0-9]{1,2}[A-Z]{3}[0-9]{0,4})\\s+TO\\s+([0-9]{1,2}[A-Z]{3}[0-9]{0,4})\\s*([A-Z0-9)(]*)\\s*(.*)$");

        //private readonly Regex cnlReg = new Regex("^([A-Z0-9]+\\))?\\s*([A-Za-z0-9/]+\\s+[A-Z-]+)\\s+(CNL RPT)*\\s*CNL(.*)$");

        //private readonly Regex acReg = new Regex("^([A-Z0-9]+\\))?\\s*(\\w{2,}.+\\s+)A/C\\s+CHG\\s+TO(.*)$");

        //private readonly Regex TRReg = new Regex("([A-Z0-9]+\\))?\\s*([A-Za-z0-9/]+\\s+[A-Z-]*)\\s*(TIME\\s+CHG\\s+TO|TM\\s+CHG\\s+TO|ROUTE\\s+CHG\\s+TO|R/T\\s+CHG\\s+TO)\\s+(.+)");

        //private readonly Regex IsBackFlight = new Regex("^([A-Z]+[0-9]+/[0-9]+).*$");

        //private readonly Regex NoBackFlight = new Regex("^([A-Z]+[0-9]+).*$");

        //private readonly Regex IsBackChange = new Regex("^([A-Z]{3})([0-9]{4})[+]*\\d*\\s+([0-9]{4})[+]*\\d*([A-Z]{3})([0-9]{4})[+]*\\d*\\s+([0-9]{4})[+]*\\d*([A-Z]{3})$");

        //private readonly Regex NoBackChange = new Regex("^([A-Z]{3})([0-9]{4})[+]*\\d*\\s+([0-9]{4})[+]*\\d*([A-Z]{3})$");



        static readonly System.Globalization.CultureInfo culture = new System.Globalization.CultureInfo("en-US", true);
        #endregion
         

        #region Implete IMessageParser

        public void Init()
        {
            IUnityContainer container = new UnityContainer();

            UnityConfigurationSection config = (UnityConfigurationSection)ConfigurationManager.GetSection("unity");

            config.Containers["Data"].Configure(container);

            IDataProvider provider = container.Resolve<IDataProvider>();

            manager = new SITAMessageManager(provider);
        }


        public void DetectAndParse(int batchSize, string messageType)
        {
            List<SITAMessage> newSourceMessageList = null;
            try
            {
                newSourceMessageList = manager.GetSourceMessageToParse(messageType, batchSize, (int)FileStatus.FinishDownload, (int)FileStatus.StartParse);
                Logger.InfoFormat("{0} messages need to parse", newSourceMessageList.Count);
            }
            //catch(exc
            catch (Exception e)
            {
                Logger.Error("error in GetSourceMessageToParse", e);
                return;
            }

            List<int> successIDs = new List<int>();
            List<int> failIDs = new List<int>();

            foreach (SITAMessage message in newSourceMessageList)
            {
                try
                {

                    bool result = parseMessage(message);

                    if (!result)
                    {
                        throw new Exception("There is NO Correct Formate Line To Parse");
                    }

                    message.ParseFinishTime = DateTime.Now;

                    message.Status = (int)(FileStatus.FinishDownload | FileStatus.FinishParse);

                    successIDs.Add(message.SourceID);

                }
                catch (Exception e)
                {
                    Logger.ErrorFormat("error in parseMessage,the messageid is :{0};error:{1}", message.SourceID, e.Message);

                    message.ParseErrorLog = string.Format(" Parse fail : {0}\n  ", e.Message) + message.ParseErrorLog;
                    message.ParseFinishTime = DateTime.Now;
                    message.Status = (int)(FileStatus.FinishDownload | FileStatus.ParseError);
                    failIDs.Add(message.SourceID);
                }

                //更新状态

                try
                {
                    manager.UpdateSourceMessageModel(message);
                }
                catch (Exception e)
                {
                    Logger.Error("Error in UpdateSourceMessageModel", e);
                }

            }

            //log
            Logger.InfoFormat("parse success {0} messages", successIDs.Count);
            Logger.InfoFormat("parse error {0} messages", failIDs.Count);


            ////更新状态
            //try
            //{

            //    manager.UpdateSourceMessageStatus(successIDs, FileStatus.FinishDownload|FileStatus.FinishParse);
            //    manager.UpdateSourceMessageStatus(failIDs, FileStatus.FinishDownload|FileStatus.ParseError);
            //}
            //catch (Exception e)
            //{
            //    Logger.Error("error in UpdateStatus", e);
            //}
        }

        private bool parseMessage(SITAMessage message)
        {
            bool IsHavContent = false;

            Match regResult;

            if (string.IsNullOrEmpty(message.SourceContent))
            {
                Logger.Warn("there is no body in message:" + message.SourceID.ToString());
                return false;
            }
            string[] contentLine = message.SourceContent.Split(new string[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries);

            bool IsHeadCorrect = true;
            if (contentLine[0].Trim().ToLower() == "asc")
            {
                IsHeadCorrect = true;
                Logger.InfoFormat("{0}:the head is standard", message.SourceID);
            }
            else
            {
                IsHeadCorrect = false;
                Logger.InfoFormat("{0}:the head is error formate", message.SourceID);
            }

            string reason = "";

            List<SITAHeadInfo> changeDateList = new List<SITAHeadInfo>();

            string unParseLine = " ";

            for (int i = 0; i < contentLine.Length; i++)
            {
                string line = contentLine[i].Trim();
                // reason
                if (line.StartsWith("BECAUSE", true, culture) || line.StartsWith("DUE TO", true, culture))
                {
                    reason = contentLine[i];
                }
                #region date
                //date
                else if ((regResult = new Regex(ConfigurationManager.AppSettings["onDateReg"]).Match(line)).Success) 
                {
                    changeDateList.Clear();

                    string dateStr = regResult.Groups[2].Value;

                    string monthAndYear = regResult.Groups[3].Value;

                    string[] dates = dateStr.Split('/');

                    foreach (string date in dates)
                    {
                        SITAHeadInfo info = new SITAHeadInfo();
                        try
                        {
                            info.ChangeStartDate = info.ChangeEndDate = ParseDateTimeStr(date + monthAndYear);
                        }
                        catch
                        {
                            throw new Exception(string.Format("DateTime Formate error at Line {0},Content is '{1}' ", i, line));
                        }
                        info.ChangeDay = ((int)info.ChangeStartDate.DayOfWeek == 0 ? 7 : (int)info.ChangeStartDate.DayOfWeek).ToString();
                        changeDateList.Add(info);
                    }
                }
                // From Date
                else if ((regResult=new Regex(ConfigurationManager.AppSettings["fmDateReg"]).Match(line)).Success)
                {
                   // Match m = fmDateReg.Match(line);

                    changeDateList.Clear();


                    DateTime totalStartDate;
                    DateTime totalEndDate;
                    string dayOfWeek = "";
                    try
                    {
                        // dateInfo.ChangeStartDate = ParseDateTimeStr(m.Groups[2].Value.Trim());
                        // dateInfo.ChangeEndDate = ParseDateTimeStr(m.Groups[3].Value.Trim());

                        totalStartDate = ParseDateTimeStr(regResult.Groups[2].Value.Trim());
                        totalEndDate = ParseDateTimeStr(regResult.Groups[3].Value.Trim());
                    }
                    catch
                    {
                        throw new Exception(string.Format("DateTime Formate error at Line {0},Content is '{1}' ", i, line));
                    }

                    string week = regResult.Groups[4].Value.Trim();

                    string exceptPart = regResult.Groups[5].Value.Trim();



                    if (week.Contains("EXCEPT"))
                    {
                        string tem = week.Replace("(", "").Replace(")", "");

                        string[] ex = exceptPart.Split(new string[] { " " }, StringSplitOptions.RemoveEmptyEntries);

                        week = ex.Length > 1 ? ex[1].Replace("(", "").Replace(")", "") : "";
                        exceptPart = tem + " " + ex[0];
                    }

                    if (week.StartsWith("DAILY"))
                    {
                        dayOfWeek = "1234567";
                    }
                    else if (week.StartsWith("D"))
                    {
                        dayOfWeek = week.Substring(1);
                    }
                    else if (week.StartsWith("EV"))
                    {
                        dayOfWeek = week.Substring(2);
                    }
                    else if (week.StartsWith("EVERY"))
                    {
                        dayOfWeek = week.Substring(5);
                    }
                     

                    exceptPart = exceptPart.Replace("(", string.Empty).Replace(")", string.Empty).Trim();

                    if (exceptPart.Contains("EXCEPT"))
                    {
                        exceptPart = exceptPart.Substring(exceptPart.IndexOf("EXCEPT") + 6).Trim();

                        Regex rg = new Regex("^([0-9/]+)([A-Z]{3}[0-9]*)$");
                        Match m1;
                        List<int> days = new List<int>();
                        if ((m1 = rg.Match(exceptPart)).Success)
                        {
                            try
                            {
                                days = m1.Groups[1].Value.Split('/').ToList<string>().ConvertAll<int>(delegate(string s) { return int.Parse(s); });
                            }
                            catch
                            {
                                throw new Exception(string.Format("DateTime Formate error at Line {0},Content is '{1}' ", i, line));
                            }
                            days.Sort();

                            DateTime sDate = totalStartDate;
                            DateTime eDate;
                            foreach (int day in days)
                            {
                                try
                                {
                                    eDate = ParseDateTimeStr(day.ToString() + m1.Groups[2].Value);
                                }
                                catch
                                {
                                    throw new Exception(string.Format("DateTime Formate error at Line {0},Content is '{1}' ", i, line));
                                }
                                if (eDate.AddDays(-1) >= sDate)
                                {
                                    SITAHeadInfo dateInfo = new SITAHeadInfo();
                                    dateInfo.ChangeStartDate = sDate;
                                    dateInfo.ChangeEndDate = eDate.AddDays(-1);
                                    dateInfo.ChangeDay = dayOfWeek;

                                    changeDateList.Add(dateInfo);
                                }

                                sDate = eDate.AddDays(1);
                            }

                            if (totalEndDate >= sDate)
                            {
                                SITAHeadInfo info = new SITAHeadInfo();
                                info.ChangeStartDate = sDate;
                                info.ChangeEndDate = totalEndDate;
                                info.ChangeDay = dayOfWeek;
                                changeDateList.Add(info);
                            }

                        }
                    }
                    else
                    {
                        SITAHeadInfo info = new SITAHeadInfo();
                        info.ChangeStartDate = totalStartDate;
                        info.ChangeEndDate = totalEndDate;
                        info.ChangeDay = dayOfWeek;
                        changeDateList.Add(info);
                    }
                }
                #endregion

                #region CNL
                else if ((regResult = new Regex(ConfigurationManager.AppSettings["cnlReg"]).Match(line)).Success)
                {
                    IsHavContent = true;

                   // Match m = cnlReg.Match(line);

                    string cnlStr = regResult.Groups[2].Value.Trim();
                    Logger.InfoFormat("CNL FLight INfo:{0}", cnlStr);
                    string arrange = (regResult.Groups[4].Value.Trim().Contains("PAX") ||
                                  regResult.Groups[4].Value.Trim().Contains("PLZ") ||
                                 regResult.Groups[4].Value.Trim().Contains("ARRANGE")) ? regResult.Groups[4].Value.Trim() : "";

                    List<SITAHeadInfo> headList = null;
                    try
                    {
                        headList = GetHead(cnlStr);
                    }
                    catch (Exception e)
                    {
                        Logger.ErrorFormat("get headInfo error, the headStr is : {0}\n Error Message:{1}\n SourceID:{2}", cnlStr, e.Message, message.SourceID);

                        message.ParseErrorLog = message.ParseErrorLog + string.Format(" Parse error at Line {0},FlightNo,AirPort formate error Content: '{1}' \n  ", i, line);
                        continue;
                    }
                    int count = 1;
                    while (true)
                    {
                        string nextLine = contentLine[i + count].Trim();
                        if (nextLine.StartsWith("PLZ") || nextLine.StartsWith("PAX") || nextLine.StartsWith("ARRANGE"))
                        {
                            arrange = arrange + nextLine + "   \n";
                        }
                        else
                        {
                            break;
                        }
                        count++;
                    }

                    List<CancleMessage> cmList = new List<CancleMessage>();

                    foreach (SITAHeadInfo dateInfo in changeDateList)
                    {
                        foreach (SITAHeadInfo head in headList)
                        {
                            CancleMessage calMessage = new CancleMessage();
                            calMessage.RefSourceID = message.SourceID;
                            calMessage.ChangeStartDate = dateInfo.ChangeStartDate;
                            calMessage.ChangeEndDate = dateInfo.ChangeEndDate;
                            calMessage.ChangeDay = dateInfo.ChangeDay;
                            calMessage.FlightNo = head.FlightNo;
                            calMessage.DeptAirport = head.DeptAirport;
                            calMessage.ArrAirport = head.ArrAirport;
                            calMessage.ArrangeComment = arrange;
                            calMessage.RealReason = reason;

                            cmList.Add(calMessage);
                        }
                    }

                    //cmList.ForEach(f => { f.RefSourceID = message.SourceID; 
                    //                      f.ChangeStartDate = ChangeStartDate;
                    //                      f.ChangeDay = DayOfWeek;
                    //                      f.ArrangeComment = arrange;
                    //                      f.RealReason = reason; });

                    try
                    {
                        manager.InsertCancleMessageList(cmList);
                    }
                    catch (Exception e)
                    {
                        Logger.Error(string.Format(" InsertCancleChangeData error at Line {0},error message: '{1}' \n  ", i, e.Message));

                        message.ParseErrorLog = message.ParseErrorLog + string.Format(" InsertCancleChangeData error at Line {0},error message: '{1}' \n  ", i, e.Message);

                    }
                    continue;
                }
                #endregion

                #region AC Change
                else if ((regResult = new Regex(ConfigurationManager.AppSettings["acReg"]).Match(line)).Success)
                {
                    IsHavContent = true;

                    string flightInfoStr = regResult.Groups[2].Value.Trim();
                    string modelInfo = regResult.Groups[3].Value.Trim();

                    string[] models = modelInfo.Split(new string[] { "ISO" }, StringSplitOptions.RemoveEmptyEntries);
                    string newModel = models[0];
                    string oldModel = models.Length > 1 ? models[1] : "";

                    // List<SITAHeadInfo> heads = GetHead(flightInfoStr);
                    List<SITAHeadInfo> heads = null;
                    try
                    {
                        heads = GetHead(flightInfoStr);
                    }
                    catch (Exception e)
                    {
                        Logger.ErrorFormat("get headInfo error, the headStr is : {0}\n Error Message:{1}\n SourceID : {2}", flightInfoStr, e.Message, message.SourceID);
                        message.ParseErrorLog = message.ParseErrorLog + string.Format(" Parse error at Line {0},FlightNo,AirPort formate error Content: '{1}' \n  ", i, line);
                        continue;
                    }

                    List<ACChangeMessage> acList = new List<ACChangeMessage>();

                    foreach (SITAHeadInfo dateInfo in changeDateList)
                    {
                        foreach (SITAHeadInfo head in heads)
                        {
                            ACChangeMessage acMessage = new ACChangeMessage();
                            acMessage.RefSourceID = message.SourceID;
                            acMessage.ChangeStartDate = dateInfo.ChangeStartDate;
                            acMessage.ChangeEndDate = dateInfo.ChangeEndDate;
                            acMessage.ChangeDay = dateInfo.ChangeDay;
                            acMessage.DeptAirport = head.DeptAirport;
                            acMessage.ArrAirport = head.ArrAirport;
                            acMessage.FlightNo = head.FlightNo;
                            acMessage.NewModel = newModel;
                            acMessage.OldModel = oldModel;
                            acMessage.RealReason = reason;
                            acList.Add(acMessage);
                        }
                    }
                    try
                    {
                        manager.InsertACChangeMessageList(acList);
                    }
                    catch (Exception e)
                    {
                        Logger.Error(string.Format(" InsertACChangeData error at Line {0},error message: '{1}' \n  ", i, e.Message));

                        message.ParseErrorLog = message.ParseErrorLog + string.Format(" InsertACChangeData error at Line {0},error message: '{1}' \n  ", i, e.Message);

                    }
                    continue;
                }
                #endregion

                #region TIME TM ROUTE TR change
                else if ((regResult = new Regex(ConfigurationManager.AppSettings["TRReg"]).Match(line)).Success)
                {
                    IsHavContent = true;

                    string FlightInfo = regResult.Groups[2].Value.Trim();
                    string ChangeInfo = regResult.Groups[4].Value.Trim();

                    string ChangeType = regResult.Groups[3].Value.Trim();

                    Match isBackMatch;

                    Match isChangeMatch = new Regex(ConfigurationManager.AppSettings["IsBackChange"]).Match(ChangeInfo);
                    //往返
                    if ((isBackMatch = new Regex(ConfigurationManager.AppSettings["IsBackFlight"]).Match(FlightInfo)).Success)
                    {
                        if (!(isChangeMatch.Success))
                        {
                            Logger.Error((string.Format("error on messageid:{0} line:{1}  change information not macth the flightNo", message.SourceID, i)));

                            message.ParseErrorLog = message.ParseErrorLog + string.Format(" Parse error at Line {0}, change information not macth the flightNo Content: '{1}' \n  ", i, line);

                            continue;
                        }

                        string flightInfo = isBackMatch.Groups[1].Value.Trim();

                        string[] flights = flightInfo.Split('/');

                        List<TRChangeMessage> trList = new List<TRChangeMessage>();

                        foreach (SITAHeadInfo dateInfo in changeDateList)
                        {
                            TRChangeMessage goChange = new TRChangeMessage();
                            goChange.FlightNo = flights[0];

                            //Match mt = IsBackChange.Match(ChangeInfo);

                            goChange.DeptAirport = isChangeMatch.Groups[1].Value;
                            goChange.DeptTime = isChangeMatch.Groups[2].Value.Substring(0, 2) + ":" + isChangeMatch.Groups[2].Value.Substring(2);

                            goChange.ArrAirport = isChangeMatch.Groups[4].Value;
                            goChange.ArrTime = isChangeMatch.Groups[3].Value.Substring(0, 2) + ":" + isChangeMatch.Groups[3].Value.Substring(2);

                            TRChangeMessage backChange = new TRChangeMessage();

                            backChange.FlightNo = flights[0].Substring(0, flights[0].Length - flights[1].Length) + flights[1];

                            backChange.DeptAirport = isChangeMatch.Groups[4].Value;
                            backChange.DeptTime = isChangeMatch.Groups[5].Value.Substring(0, 2) + ":" + isChangeMatch.Groups[2].Value.Substring(2);

                            backChange.ArrAirport = isChangeMatch.Groups[7].Value;
                            backChange.ArrTime = isChangeMatch.Groups[6].Value.Substring(0, 2) + ":" + isChangeMatch.Groups[3].Value.Substring(2);

                            goChange.RefSourceID = backChange.RefSourceID = message.SourceID;

                            goChange.ChangeStartDate = backChange.ChangeStartDate = dateInfo.ChangeStartDate;
                            goChange.ChangeEndDate = backChange.ChangeEndDate = dateInfo.ChangeEndDate;
                            goChange.ChangeDay = backChange.ChangeDay = dateInfo.ChangeDay;

                            goChange.RealReason = backChange.RealReason = reason;

                            //chagetype  ([\bTIME\bTM\b])+  根据这段里是否含有time等来判断类型

                            goChange.ChangeType = backChange.ChangeType = (ChangeType.StartsWith("TIME") || ChangeType.StartsWith("TM")) ? "TIME" : ChangeType.StartsWith("ROUTE") ? "ROUTE" : ChangeType.StartsWith("R/T") ? "R/T" : "";
                            trList.Add(goChange);
                            trList.Add(backChange);
                        }
                        try
                        {
                            manager.InsertTRChangeMessageList(trList);
                        }
                        catch (Exception e)
                        {
                            Logger.Error(string.Format(" InsertTRChangeData error at Line {0},error message: '{1}' \n  ", i, e.Message));

                            message.ParseErrorLog = message.ParseErrorLog + string.Format(" InsertTRChangeData error at Line {0},error message: '{1}' \n  ", i, e.Message);

                            // continue;
                        }

                    }
                    //单程
                    else
                    {
                        if (isChangeMatch.Success)
                        {
                            Logger.Error(string.Format("error on messageid:{0} line:{1}  change information not macth the flightNo", message.SourceID, i));

                            message.ParseErrorLog = message.ParseErrorLog + string.Format(" Parse error at Line {0}, change information not macth the flightNo Content: '{1}' \n  ", i, line);

                            continue;
                        }

                        string flightNo = new Regex(ConfigurationManager.AppSettings["NoBackFlight"]).Match(FlightInfo).Groups[1].Value;

                        Match m = new Regex(ConfigurationManager.AppSettings["NoBackChange"]).Match(ChangeInfo);

                        List<TRChangeMessage> trList = new List<TRChangeMessage>();

                        foreach (SITAHeadInfo dateInfo in changeDateList)
                        {
                            TRChangeMessage trMessage = new TRChangeMessage();

                            trMessage.DeptAirport = m.Groups[1].Value;
                            trMessage.DeptTime = m.Groups[2].Value.Substring(0, 2) + ":" + m.Groups[2].Value.Substring(2);

                            trMessage.ArrTime = m.Groups[3].Value.Substring(0, 2) + ":" + m.Groups[3].Value.Substring(2);
                            trMessage.ArrAirport = m.Groups[4].Value;

                            trMessage.RealReason = reason;
                            trMessage.RefSourceID = message.SourceID;
                            trMessage.FlightNo = flightNo;
                            trMessage.ChangeStartDate = dateInfo.ChangeStartDate;
                            trMessage.ChangeEndDate = dateInfo.ChangeEndDate;
                            trMessage.ChangeDay = dateInfo.ChangeDay;
                            trMessage.ChangeType = (ChangeType.StartsWith("TIME") || ChangeType.StartsWith("TM")) ? "TIME" : ChangeType.StartsWith("ROUTE") ? "ROUTE" : ChangeType.StartsWith("R/T") ? "R/T" : "";
                            trList.Add(trMessage);
                        }
                        try
                        {
                            manager.InsertTRChangeMessageList(trList);
                        }
                        catch (Exception e)
                        {
                            Logger.Error(string.Format(" InsertTRChangeData error at Line {0},error message: '{1}' \n  ", i, e.Message));

                            message.ParseErrorLog = message.ParseErrorLog + string.Format(" InsertTRChangeData error at Line {0},error message: '{1}' \n  ", i, e.Message);

                            // continue;
                        }
                    }
                    continue;
                }
                #endregion

                //记录下未被解析的内容
                else
                {
                    if ((i == 0 && IsHeadCorrect) || string.IsNullOrEmpty(line) || (line.StartsWith("PLZ"))||((i == contentLine.Length - 1) && line.EndsWith("=")))
                    {
                        continue;
                    }
                    unParseLine += string.Format("  UnParseLine:Line {0},Content:'{1}' \n", i, line);
                }
            }
            message.ParseErrorLog += unParseLine;

            return IsHavContent;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="dateStr"></param>
        /// <returns></returns>
        private DateTime ParseDateTimeStr(string dateStr)
        {
            if (dateStr.Length == 4)
            {
                return DateTime.ParseExact(dateStr, "dMMM", culture);

            }
            else if (dateStr.Length == 5)
            {
                return DateTime.ParseExact(dateStr, "ddMMM", culture);
            }
            else if (dateStr.Length == 7)
            {
                return DateTime.ParseExact(dateStr, "ddMMMyy", culture);
            }
            else if (dateStr.Length == 9)
            {
                return DateTime.ParseExact(dateStr, "ddMMMyyyy", culture);
            }
            else
            {
                throw new Exception("the Date Formate is Error");
            }
        }

        private List<SITAHeadInfo> GetHead(string cnlStr)
        {

            Match m = new Regex(ConfigurationManager.AppSettings["flightAirportReg"]).Match(cnlStr);


            if (m.Groups.Count < 2)
            {
                throw new Exception("FlightNo,AirPort formate error");
            }
            //航班号 
            string[] flights = m.Groups[1].Value.Split('/');

            //机场
            string[] airPorts = m.Groups[2].Value.Split('-');

            string baseFlight = flights[0].Trim();

            List<SITAHeadInfo> reslut = new List<SITAHeadInfo>();
            for (int i = 0; i < flights.Length; i++)
            {
                SITAHeadInfo me = new SITAHeadInfo();
                me.FlightNo = baseFlight.Substring(0, baseFlight.Length - flights[i].Length) + flights[i];
                me.DeptAirport = airPorts[i];
                me.ArrAirport = airPorts[i + 1];
                reslut.Add(me);
            }
            return reslut;
        }

        #endregion
    }
}
